import React, { useState, useRef, useEffect } from 'react';

interface SearchBarProps {
  onSearch: (keyword: string) => void;
  searchHistory: string[];
}

function SearchBar({ onSearch, searchHistory }: SearchBarProps) {
  const [keyword, setKeyword] = useState('');
  const [showHistory, setShowHistory] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(-1);
  const inputRef = useRef<HTMLInputElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setShowHistory(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (keyword.trim()) {
      onSearch(keyword.trim());
      setShowHistory(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (showHistory && searchHistory.length > 0) {
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        setSelectedIndex(prev => 
          prev < searchHistory.length - 1 ? prev + 1 : prev
        );
      } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        setSelectedIndex(prev => prev > -1 ? prev - 1 : -1);
      } else if (e.key === 'Enter' && selectedIndex >= 0) {
        e.preventDefault();
        const selectedKeyword = searchHistory[selectedIndex];
        setKeyword(selectedKeyword);
        onSearch(selectedKeyword);
        setShowHistory(false);
        setSelectedIndex(-1);
      }
    }
  };

  const handleHistoryClick = (historyItem: string) => {
    setKeyword(historyItem);
    onSearch(historyItem);
    setShowHistory(false);
  };

  return (
    <div className="max-w-2xl mx-auto relative" ref={containerRef}>
      <form onSubmit={handleSubmit}>
        <div className="relative">
          <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
            <svg
              className="h-5 w-5 text-gray-400"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
              />
            </svg>
          </div>
          <input
            ref={inputRef}
            type="text"
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
            onFocus={() => setShowHistory(true)}
            onKeyDown={handleKeyDown}
            className="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-primary-500 focus:border-primary-500 sm:text-sm"
            placeholder="输入关键词搜索软件，如：视频剪辑、图片处理..."
          />
          <div className="absolute inset-y-0 right-0 pr-3 flex items-center">
            <button
              type="submit"
              className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
            >
              搜索
            </button>
          </div>
        </div>
      </form>

      {showHistory && searchHistory.length > 0 && (
        <div className="absolute z-10 mt-1 w-full bg-white shadow-lg max-h-60 rounded-md py-1 text-base overflow-auto ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm">
          {searchHistory.map((item, index) => (
            <div
              key={item}
              className={`cursor-pointer select-none relative py-2 pl-3 pr-9 ${
                index === selectedIndex ? 'text-white bg-primary-600' : 'text-gray-900'
              }`}
              onClick={() => handleHistoryClick(item)}
            >
              <span className="font-normal block truncate">{item}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

export default SearchBar;
